"use strict";

var C = require('../common'),
    AuthModule = require('../nodeauth');

module.exports = AuthModule.extend({
}, {
    setup: function (manager, webModule, runtime, cb) {
        var options = runtime.options;

        var loginField = options.loginField || 'username';
        var passwordField = options.passwordField || 'password';

        AuthModule.setup(manager, webModule, runtime, function (err) {
            if (err) return cb(err);

            var loginControllerPath = options.loginControllerPath || options.loginPagePath;
            loginControllerPath || C.throwRequired('auth[' + runtime.controllerName + '].loginControllerPath');

            var authenticate = runtime.controller.authenticate;
            if (!authenticate) {
                throw new C.Error.UsageError('Require "authenticate" action in auth controller of "' + runtime.controllerName + '".');
            }

            function login(router) {
                var data = router.req.body;
                var login = data[loginField];
                var password = data[passwordField];

                authenticate(router, login, password, function (err, user, extra) {
                    if (err) throw err; //return router.handleError(err);

                    var authModule = manager.createInstance(router, runtime.controllerName);
                    authModule.signIn(user, extra);
                });
            }

            manager.mountController(C.urlJoin(webModule.route, loginControllerPath), login, 'post');

            cb();
        });
    }
});